<?php
/**
 * Created by PhpStorm.
 * User: shiding
 * Date: 2019-06-24
 * Time: 17:03
 */

namespace App\Http\Repositories;

use App\Models\Articles;
use App\Models\ArticlesTag;
use App\Models\Tag;
use Illuminate\Support\Facades\DB;

class ArticlesRepository
{
    protected $articlesModel;
    protected $articlesTagModel;
    protected $tagModel;

    public function __construct(Articles $articles, ArticlesTag $articlesTag, Tag $tag)
    {
        $this->articlesModel = $articles;
        $this->articlesTagModel = $articlesTag;
        $this->tagModel = $tag;
    }

    public function getList($params)
    {
        return $this->articlesModel->getList($params);
    }

    public function getArchive()
    {
       return $this->articlesModel->getArchive()->groupBy("day");
    }

    public function changeEnable($id, $status)
    {
        return $this->articlesModel->changeEnable($id, $status);
    }

    public function edit($params, $tag, $id = 0)
    {
        try {
            DB::beginTransaction();
            if (empty($id)) {
                $articlesId = $this->articlesModel->insertGetId($params);
                $this->articleTag($articlesId, $tag);
            } else {
                $this->articlesModel->where("id", $id)->update($params);
                $this->articleTag($id, $tag);
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
    }

    public function articleTag($id, $tag)
    {
        $arr = explode(",", $tag);
        $tagIdArr = [];
        foreach ($arr as $v) {
            $checkTag = $this->tagModel->where('name', $v)->first();
            if (empty($checkTag)) {
                $tagId = $this->tagModel->insertGetId(["name" => $v]);
                array_push($tagIdArr, ['tag_id' => $tagId]);
            } else {
                array_push($tagIdArr, ['tag_id' => $checkTag->id]);
            }
        }
        array_walk($tagIdArr, function(&$item) use ($id) {
            $item["articles_id"] = $id;
        });
        $check = $this->articlesTagModel->where("articles_id", $id)->get();

        $check && $this->articlesTagModel->where("articles_id", $id)->delete();
        $this->articlesTagModel->insert($tagIdArr);
    }

    public function del($id)
    {
        return $this->articlesModel->destroy($id);
    }

    public function getHotArticles()
    {
        return $this->articlesModel->getHotArticles();
    }

    public function getCount()
    {
        return  $this->articlesModel->count();
    }
}